package com.example.udpDemo.socket.udp;

import cn.hutool.core.util.HexUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * @author wangdachuan
 * @version 1.0
 * @date 2023/3/14 23:12
 **/
@Slf4j
@Component
public class UdpServerHandler  extends SimpleChannelInboundHandler<DatagramPacket> {

    @Override
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, DatagramPacket datagramPacket)
            throws Exception {
        InetSocketAddress sender = datagramPacket.sender();
        String ip = sender.getAddress().getHostAddress();
        ByteBuf buf = datagramPacket.copy().content();
        try {
            byte[] data = new byte[buf.readableBytes()];
            buf.readBytes(data);
            String dataStr = HexUtil.encodeHexStr(data);
            log.info("收到IP：{},发送的数据：{}", ip, dataStr);
            // 下面进行业务代码处理
        }catch (Exception e){
            e.printStackTrace();
        }
        // TCP返回数据写法
        //channelHandlerContext.channel().writeAndFlush("1");
        // UDP返回数据写法
        channelHandlerContext.channel().writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(HexUtil.decodeHex("1")), datagramPacket.sender()));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
    }
}
